#!/usr/bin/env python3
# coding=utf-8

from http.server import HTTPServer, BaseHTTPRequestHandler
import json 
import psutil
import time
host = ('0.0.0.0', 10105)

class Resquest(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        cpu = psutil.cpu_percent()
        cpu_memory=psutil.virtual_memory()
        all = round(cpu_memory.total/1024/1024/1024,2)
        used = round(cpu_memory.used/1024/1024/1024,2)
        free = round(cpu_memory.free/1024/1024/1024,2)
        data = {'result':'success','code':200,'cpu':cpu,'mem':all, 'used': round(used/all*100,2), "free":round(free/all,2)*100}
        self.wfile.write(json.dumps(data).encode("utf-8"))

if __name__ == '__main__':
    server = HTTPServer(host, Resquest)
    _msg = '[' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ']Starting Server....'
    f = './tmp/supan_web_server_' + time.strftime("%Y-%m-%d", time.localtime()) + '.log'
    with open(f,"a") as file:
        file.write(_msg+"\n")
        file.close()
    server.serve_forever()